import { cloneDeep } from 'lodash';

interface ButtonStructure {
  action: string;
  name?: string;
  type?: string;
  styleType?: string;
  bgColor?: string;
  fontColor?: string;
  taskType?: string;
}

const getMembers = (inbiz, pageValue, paramsValue, varName, key) => {
  const pcControlIdValue: any = pageValue[key];
  if (pcControlIdValue || pcControlIdValue == 0) {
    // 如果有值
    if (inbiz(key).componentType == 'EformMemberSelect') {
      // 组件是成员选择组件
      // const values = pcControlIdValue.map((item) => item.Id || item.ID || ).join(',');
      const values = pcControlIdValue.map((item) => item.id).join(',');
      paramsValue.push({
        name: varName,
        value: values,
      });
    } else {
      paramsValue.push({
        name: varName,
        value: Array.isArray(pcControlIdValue) ? pcControlIdValue.join() : pcControlIdValue,
      });
    }
  }
  return paramsValue;
};

export const getvars = (pageValue: { [index: string]: string }, inbiz, type, processvars?) => {
  let paramsValue: { name: string; value: string }[] = [];
  if (inbiz?.workFlow?.bpmnVarEntities) {
    for (let index = 0; index < inbiz?.workFlow?.bpmnVarEntities.length; index++) {
      const element = inbiz?.workFlow?.bpmnVarEntities[index];
      const { pcControlId, moveControlId, varName } = element;
      if (type == 'web' && pcControlId && varName) {
        // pc变量
        paramsValue = getMembers(inbiz, pageValue, paramsValue, varName, pcControlId);
      } else if (type == 'wap' && moveControlId && varName) {
        // 移动端变量
        paramsValue = getMembers(inbiz, pageValue, paramsValue, varName, moveControlId);
      }
      if (
        varName &&
        processvars &&
        (processvars.current[varName] || processvars.current[varName] == 0)
      ) {
        // 扩展代码设置变量, 防止只有变量名没有变量值
        paramsValue.push({
          name: varName,
          value: processvars.current[varName],
        });
      };
    };
  } else {
    if (processvars?.current) {
      for (const key in processvars?.current) {
        paramsValue.push({
          name: key,
          value: processvars.current[key],
        });
      };
    };
  }
  return paramsValue;
};

const buttonIndex = (buttons: ButtonStructure[], action: string) => {
  const index = buttons.findIndex((item) => item.action == action);
  return index;
};

export const filterBtns = ({
  isNewVersionDesigner,
  taskId,
  buttons,
  inbiz,
  tabKey,
  showDraft,
  showWithdraw,
  hiddenButtons,
  showIsUrge,
  IncidentState,
  initialTaskState,
}: {
  isNewVersionDesigner: boolean,
  taskId?: string | undefined,
  buttons: ButtonStructure[];
  inbiz: any;
  tabKey: string;
  showDraft: boolean;
  showIsUrge: boolean;
  showWithdraw: boolean;
  hiddenButtons: any[];
  IncidentState?: string | number;
  initialTaskState?: string;
}) => {
  const batchApproval = sessionStorage.getItem('batchApproval');
  const newarr = isNewVersionDesigner ? buttons : buttons.reduce((item, next) => {
    const index = item.find((ele) => ele.action == next.action);
    if (!index) {
      item.push(next);
    }
    return item;
  }, []);
  const cloneButtons = [
    ...cloneDeep(newarr),
    {
      name: 'processButton.submit',
      action: 'submit',
    },
  ];
  let newButtons: ButtonStructure[] = [];
  let array1: ButtonStructure[] = [];
  let array2: ButtonStructure[] = [];
  let canReturn = false;
  const returnStarter = isNewVersionDesigner ? inbiz?.workFlow?.buttonSetting?.returnsBackButtonConfig?.find((item) => item?.action == 'returnStarter')?.enable : inbiz?.workFlow?.returnStarter;
  const cdirectBack = isNewVersionDesigner ? inbiz?.workFlow?.buttonSetting?.returnsBackButtonConfig?.find((item) => item?.action == 'cdirectBack')?.enable : inbiz?.workFlow.cdirectBack;
  const activityNo = isNewVersionDesigner ? inbiz?.workFlow?.baseInfo?.activityNo : inbiz?.workFlow.activityNo;
  const plusSign = isNewVersionDesigner ? inbiz?.workFlow?.buttonSetting?.plusSign : inbiz?.workFlow?.plusSign;
  const plusSignLogic = isNewVersionDesigner ? inbiz?.workFlow?.buttonSetting?.plusSignLogic : inbiz?.workFlow?.plusSignLogic;
  // 此处根据入口筛选按钮
  switch (tabKey) {
    case '-1':
      if (IncidentState == 0) {
        newButtons = cloneButtons.filter((item) => item.action == 'cancel');
      } else {
        newButtons = [];
      }
      break;
    case '2':
      // 这么做只是把打印和自定义按钮放到最后而已
      array1 = cloneButtons.filter(
        (item) =>
          item.action == 'assign' ||
          item.action == 'submit' ||
          item.action == 'approve' ||
          item.action == 'returnsBack' ||
          item.action == 'returnsStarter' ||
          item.action == 'returnsStartModify' ||
          item.action == 'cancel' ||
          item.action == 'refuse' ||
          item.action == 'plusSign' ||
          item.action == 'fowardPlusSign' ||
          item.action == 'backwardPlusSign',
      );
      array2 = cloneButtons.filter((item) => item.action == 'print' || item.action == 'custom');
      newButtons = [...array1, ...array2];
      break;
    case '6':
    case '3':
      array1 = cloneButtons.filter((item) => item.action == 'withDraw' || item.action == 'isUrge');
      array2 = cloneButtons.filter((item) => item.action == 'print' || item.action == 'custom');
      newButtons = [...array1, ...array2];
      break;
    case '7':
      array1 = cloneButtons.filter((item) => item.action == 'cancel');
      array2 = cloneButtons.filter((item) => item.action == 'print' || item.action == 'custom');
      newButtons = [...array1, ...array2];
      break;
    case '5':
      newButtons = [];
      canReturn = true;
    case '8':
      newButtons = cloneButtons.filter((item) => item.action == 'custom');
      canReturn = true;
      break;
    case '4':
    case '1':
      newButtons = cloneButtons.filter((ele: ButtonStructure) => {
        return ele.action == 'initiate' || ele.action == 'draft' || ele.action == 'custom';
      });
      break;
    default:
      newButtons = cloneButtons;
      break;
  }
  let btns: ButtonStructure[] = newButtons;
  if (!canReturn) {
    // 此处开始根据接口返回数据筛选按钮
    if (!showDraft && buttonIndex(buttons, 'draft') > -1 && !isNewVersionDesigner) {
      btns = newButtons.filter((item) => item.action !== 'draft');
    }
    if (!showWithdraw && buttonIndex(buttons, 'withDraw') > -1 && !isNewVersionDesigner) {
      btns = btns.filter((item) => item.action !== 'withDraw');
      array1 = btns.filter((item) => item.action !== 'print' && item.action !== 'custom');
      array2 = btns.filter((item) => item.action == 'print' || item.action == 'custom');
      btns = [...array1, ...array2];
    }
    if (!showIsUrge && buttonIndex(buttons, 'isUrge') > -1 && !isNewVersionDesigner) {
      btns = btns.filter((item) => item.action !== 'isUrge');
      array1 = btns.filter((item) => item.action !== 'print' && item.action !== 'custom');
      array2 = btns.filter((item) => item.action == 'print' || item.action == 'custom');
      btns = [...array1, ...array2];
    }
    if (inbiz && inbiz?.workFlow) {
      if (inbiz?.workFlow?.subProcess) {
        btns = btns.filter((item) => item.action !== 'cancel');
      }
      if (!returnStarter) {
        btns = btns.filter((item) => item.action !== 'returnsStarter');
      }
      if (!cdirectBack) {
        btns = btns.filter((item) => item.action !== 'returnsStartModify');
      }
      if (inbiz?.workFlow?.done && tabKey == '2') {
        btns = [];
      }

      if (activityNo == 'firstTask') {
        if (taskId) {
          // 被退回
          const submitButton = btns.filter((item) => item.action == 'submit');
          const cancelButton = btns.filter((item) => item.action == 'cancel');
          const otherButton = btns.filter(
            (item) => item.action == 'print' || item.action == 'custom',
          );
          btns = [...submitButton, ...cancelButton, ...otherButton];
        } else {
          const initiateButton = btns.filter((item) => item.action == 'initiate');
          const draftButton = btns.filter((item) => item.action == 'draft');
          const withDrawButton = btns.filter((item) => item.action == 'withDraw');
          const isUrgeButton = btns.filter((item) => item.action == 'isUrge');
          const cancelButton = btns.filter((item) => item.action == 'cancel');
          const otherButton = btns.filter(
            (item) => item.action == 'print' || item.action == 'custom',
          );
          btns = [...initiateButton, ...draftButton, ...withDrawButton, ...isUrgeButton, ...cancelButton, ...otherButton];
        }
      } else if (inbiz?.workFlow?.notCurrentUser && tabKey != '-1') {
        btns = [];
      } else {
        btns = btns.filter((item) => item.action !== 'submit');
        if (inbiz?.workFlow?.activityId && inbiz?.workFlow?.activityId.includes('ctSign')) {
          //会签
          array1 = btns.filter(
            (item) =>
              item.action == 'approve' ||
              item.action == 'returnsBack' ||
              item.action == 'returnsStarter' ||
              item.action == 'returnsStartModify',
          );
          array2 = btns.filter((item) => item.action == 'custom' || item.action == 'print');
          const i = array1.findIndex((ele) => ele.action == 'approve');
          if (i > -1) {
            array1.splice(i + 1, 0, {
              name: 'processButton.refuse',
              action: 'refuse',
            });
          }
          btns = [...array1, ...array2];
        }
      }
      if (
        plusSign && // 允许加签
        plusSignLogic == 'skipNext' && // 是后加签
        buttonIndex(buttons, 'fowardPlusSign') > -1 // 判断有没有前加签, 有就删掉, 保留后加签
      ) {
        btns = btns.filter((item) => item.action !== 'fowardPlusSign');
      }
      if (
        plusSign && // 允许加签
        plusSignLogic == 'skipCurrent' && // 是前加签
        buttonIndex(buttons, 'backwardPlusSign') > -1 // 判断有没有后加签, 有就删掉  保留前加签
      ) {
        btns = btns.filter((item) => item.action !== 'backwardPlusSign');
      }
      if (!plusSign) {
        btns = btns.filter(
          (item) =>
            item.action !== 'plusSign' &&
            item.action !== 'fowardPlusSign' &&
            item.action !== 'backwardPlusSign',
        );
      }

      if (activityNo == 'sign') {
        // 被加签
        btns = btns.filter((item) => item.action == 'approve' || item.action == 'cancel');
      }
    }
    if (batchApproval) {
      btns = [];
    }
  }
  btns = btns.filter((item) => !hiddenButtons.includes(item.action));
  if (
    tabKey == '2' &&
    // initialTaskState &&
    !(
      initialTaskState == undefined ||
      initialTaskState == '0' ||
      initialTaskState == '10' ||
      initialTaskState == '30' ||
      initialTaskState == '50' ||
      initialTaskState == '130'
    )
  ) {
    btns = [];
  }
  return btns;
};
